import { ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { useState } from 'react';
import { addItem, delItem, detailItem, getList, updateItem } from '@/services/system/role';
import { getOptionBtn } from '@/util/table';
import { AUTH_TYPE, MENU_CODES } from '@/options';
import { updateResource } from '@/services/system/login';
import { MSG } from '@/util/msg';
import RoleForm from './roleForm';
import useAuth from '@/hooks/useAuth';
import usePageVariable from '@/hooks/usePageVariable';
import MyIcon from '@/components/MyIcon';
import MyPageContainer from '@/components/MyPageContainer';
import MyScrollTable from '@/components/MyScrollTable';
import MyForm from '@/components/MyForm';
import MyOrgSelect from '@/components/MyOrgSelect';
import useDefaultColumn from '@/hooks/useDefaultColumn';

type DataType = ROLE_TYPE.Info;
const TableList: React.FC = () => {
  const [roleModel, setRoleModel] = useState(false);
  const { insertAuth, updateAuth, detailAuth, delAuth, hasAuth } = useAuth(MENU_CODES.ROLE);
  const defaultColumn = useDefaultColumn();
  const {
    formModel,
    setFormModel,
    formType,
    actionRef,
    formRef,
    currentRow,
    setCurrentRow,
    finishMsg,
    columns,
    changeForm,
    getFormTitle,
    delMsgOpen,
    setDelMsgOpen,
  } = usePageVariable<DataType>([
    defaultColumn.index,
    defaultColumn.title,
    defaultColumn.org,
    defaultColumn.searchOrg,
    defaultColumn.createTime,
    defaultColumn.updateTime,
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        hasAuth(AUTH_TYPE.ALLOT) && (
          <Button
            key={AUTH_TYPE.ALLOT}
            type="link"
            className="px-0 flex-center"
            onClick={(e) => {
              e.stopPropagation();
              setCurrentRow(record);
              setRoleModel(true);
            }}
          >
            <MyIcon name="FormOutlined" /> 分配权限
          </Button>
        ),
        updateAuth && getOptionBtn(AUTH_TYPE.UPDATE, () => changeForm(record, '1')),
        detailAuth && getOptionBtn(AUTH_TYPE.DETAIL, () => changeForm(record, '2')),
        delAuth && getOptionBtn(AUTH_TYPE.DELETE, () => changeForm(record, '3')),
      ],
    },
  ]);
  const delCall = () =>
    finishMsg(async () => {
      const ret = await delItem(currentRow!.id);
      setDelMsgOpen(false);
      if (ret.success) actionRef.current?.reload();
    });

  const onFinish = async (value: DataType) => {
    if (formType === '2') {
      setFormModel(false);
      return;
    }
    await finishMsg(async () => {
      await (formType === '1'
        ? updateItem({
            ...value,
            id: currentRow!.id,
          })
        : addItem(value));
      setFormModel(false);
      actionRef.current?.reload();
      formRef.current?.resetFields();
    });
  };
  const getFieldProps = (len: number) => {
    if (formType === '2') return undefined;
    return {
      maxLength: len,
      showCount: true,
    };
  };
  return (
    <MyPageContainer modelOk={delCall} delMsgOpen={delMsgOpen} modelCancel={setDelMsgOpen}>
      <MyScrollTable<DataType, PageParams>
        actionRef={actionRef}
        request={getList}
        columns={columns}
        clickAdd={changeForm}
        isAdd={insertAuth}
        toolBarRender={() => [
          hasAuth(AUTH_TYPE.ALLOT) && (
            <Button
              type="primary"
              key="primary"
              onClick={() =>
                finishMsg(updateResource, {
                  messageTitle: {
                    success: MSG.RENEW_SUCCESS,
                    error: MSG.RENEW_ERROR,
                    loading: MSG.RENEW_LOADING,
                  },
                })
              }
            >
              <MyIcon name="RedoOutlined" /> 更新缓存
            </Button>
          ),
        ]}
      />
      <MyForm
        formRef={formRef}
        title={getFormTitle()}
        open={formModel}
        request={currentRow?.id ? () => detailItem(currentRow!.id) : undefined}
        onOpenChange={setFormModel}
        onFinish={onFinish}
        readonly={formType === '2'}
      >
        <ProFormText
          label="名称"
          name="title"
          fieldProps={getFieldProps(30)}
          rules={[
            {
              required: true,
              message: '名称为必填项',
            },
          ]}
        />
        <MyOrgSelect />
        <ProFormTextArea label="描述" name="note" fieldProps={getFieldProps(120)} />
      </MyForm>
      {roleModel && (
        <RoleForm id={currentRow!.id} roleModel={roleModel} setRoleModel={setRoleModel} />
      )}
    </MyPageContainer>
  );
};

export default TableList;
